import { Button, Card, Flex, notification, Popconfirm, TablePaginationConfig } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import roleService from '@/api/services/security/roleService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { PermissionSelect, PermissionSelectModalProps } from '@/components/select';
import AdvancedSearchForm, { SearchForm } from '@/pages/management/system/role/search-form';
import ProTag from '@/theme/antd/components/tag';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { RoleModal, RoleModalProps } from './role-modal';

import { ListData, Role, UserInfo } from '#/entity';
import { BasicStatus } from '#/enum';

const DEFAULT_ROLE_VALUE: Role = {
  id: 0,
  createAt: [],
  name: '',
  code: '',
  status: BasicStatus.ENABLE,
};

export default function RolePage() {
  const [searchForm, setSearchForm] = useState<SearchForm>({
    page: 1,
    take: 10,
  });
  const [tableData, setTableData] = useState<ListData<Role>>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [roleModalPros, setRoleModalProps] = useState<RoleModalProps>({
    formValue: { ...DEFAULT_ROLE_VALUE },
    title: '创建角色',
    show: false,
    onOk: () => {
      setRoleModalProps((prev) => ({ ...prev, show: false }));
      onFinish([]);
    },
    onCancel: () => {
      setRoleModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const [permissionSelectModalPros, setPermissionSelectModalPros] =
    useState<PermissionSelectModalProps>({
      role: { ...DEFAULT_ROLE_VALUE },
      title: '选择权限',
      show: false,
      onOk: () => {
        setPermissionSelectModalPros((prev) => ({ ...prev, show: false }));
      },
      onCancel: () => {
        setPermissionSelectModalPros((prev) => ({ ...prev, show: false }));
      },
    });

  useEffect(() => {
    roleService.getRoleList(searchForm).then((data) => {
      setTableData(data);
      setSelectedRowKeys([]);
    });
  }, [searchForm]);
  const columns: ColumnsType<Role> = [
    {
      title: '编码',
      dataIndex: 'code',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (status) => (
        <ProTag color={status === BasicStatus.DISABLE ? 'error' : 'success'}>
          {status === BasicStatus.DISABLE ? '禁用' : '启动'}
        </ProTag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      width: 200,
      render: (createAt: number[]) => datetime(createAt),
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      width: 200,
      render: (createBy: UserInfo) => createBy.name,
    },
    { title: '备注', dataIndex: 'remark' },
    {
      fixed: 'right',
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          {hasPermission('SECURITY:ROLE:ASSIGN') && (
            <TipIconButton tipText="分配权限" onClick={() => onAssign(record)}>
              <Iconify icon="flowbite:align-justify-outline" size={18} />
            </TipIconButton>
          )}
          {hasPermission('SECURITY:ROLE:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="编辑">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('SECURITY:ROLE:DELETE') && (
            <Popconfirm
              title="确认删除角色？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  const onAssign = (item: Role) => {
    setPermissionSelectModalPros((prev) => ({
      ...prev,
      show: true,
      role: item,
      title: '选择权限',
    }));
  };
  const onDelete = (item: Role) => {
    roleService.deleteRole(item.id).then((res) => {
      if (res > 0) {
        setSearchForm((prev) => ({
          ...prev,
          page: 1,
        }));
      } else {
        notification.error({ message: '删除失败，请联系管理员' });
      }
    });
  };

  const onCreate = () => {
    setRoleModalProps((prev) => ({
      ...prev,
      show: true,
      title: '创建角色',
      formValue: {
        ...prev.formValue,
        ...DEFAULT_ROLE_VALUE,
      },
    }));
  };

  const onEdit = (formValue: Role) => {
    setRoleModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改角色',
      formValue,
    }));
  };

  const paginationConfig: TablePaginationConfig = {
    current: searchForm.page,
    pageSize: searchForm.take,
    pageSizeOptions: [5, 10, 20, 50],
    defaultPageSize: 5,
    total: tableData?.count,
    showQuickJumper: true,
    showTotal: (total) => {
      return `共 ${total} 条`;
    },
    onChange: (page, rows) => {
      setSearchForm((prev) => ({
        ...prev,
        page,
        take: rows,
      }));
    },
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<Role> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const onFinish = (values: any) => {
    setSearchForm((prev) => ({
      ...prev,
      ...values,
    }));
  };

  const enable = () => {
    if (selectedRowKeys.length <= 0) {
      notification.error({ message: '请选择要启用的角色' });
      return;
    }
    roleService.enableRole({ ids: selectedRowKeys }).then((res) => {
      res > 0 ? onFinish([]) : notification.error({ message: '启用失败' });
    });
  };
  const disable = () => {
    if (selectedRowKeys.length <= 0) {
      notification.error({ message: '请选择要禁用的角色' });
      return;
    }
    roleService.disableRole({ ids: selectedRowKeys }).then((res) => {
      res > 0 ? onFinish([]) : notification.error({ message: '禁用失败' });
    });
  };
  const reset = () => {
    setSearchForm({ page: 1, take: 10 });
  };

  return (
    <>
      <AdvancedSearchForm onOk={onFinish} onReset={reset} />
      <br />
      <Card
        title="角色信息"
        extra={
          <Flex gap="small" wrap>
            {hasPermission('SECURITY:ROLE:CREATE') && (
              <Button type="primary" variant="outlined" onClick={onCreate}>
                新增
              </Button>
            )}
            {hasPermission('SECURITY:ROLE:ENABLE') && (
              <Popconfirm
                title="确认启用角色？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => {
                  enable();
                }}
                placement="left"
              >
                <Button color="default" variant="outlined">
                  启用
                </Button>
              </Popconfirm>
            )}
            {hasPermission('SECURITY:ROLE:DISABLE') && (
              <Popconfirm
                title="确认禁用角色？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => {
                  disable();
                }}
                placement="left"
              >
                <Button color="default" variant="outlined">
                  禁用
                </Button>
              </Popconfirm>
            )}
          </Flex>
        }
      >
        <Table<Role>
          rowKey="id"
          size="small"
          rowSelection={rowSelection}
          scroll={{ x: 'max-content' }}
          pagination={paginationConfig}
          columns={columns}
          dataSource={tableData?.data}
        />
        <RoleModal {...roleModalPros} />
        {hasPermission('SECURITY:ROLE:ASSIGN') && hasPermission('SECURITY:ROLE:UPDATE') && (
          <PermissionSelect {...permissionSelectModalPros} />
        )}
      </Card>
    </>
  );
}
